﻿/*
    c1. 为示例（参见第4章课件第9页）中的泛型链表类添加类似于List<T>类
    的ForEach(Action<T> action)方法。通过调用这个方法打印链表元素，求
    最大值、最小值和求和（使用lambda表达式实现）。
 */
public class Node<T>
{
    public Node<T> Next { get; set; }
    public T Data { get; set; }

    public Node(T t)
    {
        Next = null;
        Data = t;
    }
}
public class GenericList<T>
{
    private Node<T> head;
    private Node<T> tail;

    public GenericList()
    {
        tail = head = null;
    }
    public Node<T> Head
    {
        get => head;
    }
    public void Add(T t)
    {
        Node<T> n = new Node<T>(t);
        if(tail == null)
            tail = head = n;
        else
        {
            tail.Next = n;
            tail = n;
        }
    }

    public void ForEach(Action<T> action)
    {
        Node<T> p = head;
        Node<T> q = head.Next;

        while(q != null)
        {
            action(p.Data);
            p = q;
            q = q.Next;
        }
        action(p.Data);
    }
}
public class test
{
    public static void Main(string[] args)
    {
        int sum = 0;
        int max=0, min=32767;
        Random random = new Random();   
        GenericList<int> intlist= new GenericList<int>();
        for(int i=0;i<10;i++)
        {
            intlist.Add(random.Next(100));
        }
        intlist.ForEach(a =>
        {
            Console.WriteLine(a);
            sum += a;
            if(max<a)max = a;
            if(min>a)min = a;
        });
        Console.WriteLine($"sum:{sum}");
        Console.WriteLine($"max:{max}");
        Console.WriteLine($"min:{min}");

    }
}
